﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Mathematics;

namespace FreeGoo.GameEngine.Renderables.BodyHookOwners
{
    public class Motor : BodyHookOwner
    {
        public Motor(Geom geom, Vector2 center, float hookRadius, int hookCount)
            : base(geom)
        {
            CreateBodyHooks(center, hookRadius, hookCount);
        }

        public float Torque { get; set; }
        public float TargetAngularVelocity { get; set; }

        public override void UpdatePhysics()
        {
            base.UpdatePhysics();

            Body.AngularVelocity = TargetAngularVelocity;
        }

        public override void AddToEngine(Engine engine)
        {
            base.AddToEngine(engine);
            foreach (BodyHook hook in Hooks)
            {
                engine.Add(hook);
            }
        }

        public override void Delete()
        {
            base.Delete();
            foreach (BodyHook hook in Hooks)
            {
                hook.Delete();
            }

            Hooks.Clear();
        }

        private void CreateBodyHooks(Vector2 center, float hookRadius, int hookCount)
        {
            for (int i = 0; i < hookCount; i++)
            {
                double ang = i * 2 * Math.PI / hookCount;

                Vector2 pos = center + new Vector2((float)Math.Cos(ang), (float)Math.Sin(ang)) * hookRadius;
                BodyHook hook = new BodyHook(this, pos, 4);
                AddHook(hook);
            }
        }
    }
}
